//
//  CustomFlowLayout.swift
//  JourneyThroughTime
//
//  Created by iOS-Czz on 2023/11/4.
//

import UIKit

class CustomFlowLayout: UICollectionViewFlowLayout {
    override var collectionViewContentSize: CGSize {
        guard let collectionView = collectionView else { return .zero }
        let numberOfItems = collectionView.numberOfItems(inSection: 0)
        let contentHeight = CGFloat(numberOfItems) * 160 + CGFloat(numberOfItems - 1) * 30 // 每个单元格高度为 220，重叠部分高度为 30
        return CGSize(width: collectionView.bounds.width, height: contentHeight)
    }

    override func prepare() {
        super.prepare()
        scrollDirection = .vertical
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
    }

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let collectionView = collectionView, let attributes = super.layoutAttributesForElements(in: rect) else { return nil }

        for (index, attribute) in attributes.enumerated() {
            var frame = attribute.frame
            frame.size.width = UIScreen.main.bounds.width - 30
            frame.size.height = 160

            if index != 0 {
                frame.origin.y = attributes[index - 1].frame.maxY - 50
                frame.origin.x = 0 // 不改变 x 值
            }
            attribute.frame = frame
        }

        return attributes
    }


}

